﻿using Autofac;
using NLog;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sample.Jobs
{
    
    public class SampleSchedule
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 注册窗口
        /// </summary>
        private IContainer Container;

        public SampleSchedule(IContainer container) {
            Container = container;
        }

        public async Task Start()
        {
            Console.WriteLine("SampleSchedule Started!");
            logger.Info("SampleSchedule Started!");
            
            await AddMyJob1Async();
        }

        public async Task AddMyJob1Async() {
            var job = JobBuilder.Create<MyJob1>().Build();
            var trigger = TriggerBuilder.Create()
                //.WithIdentity("Heartbeat", "Maintenance")
                .StartNow()
                .WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForever(2)).Build();
            var cts = new CancellationTokenSource();

            var scheduler = Container.Resolve<IScheduler>();
            await scheduler.ScheduleJob(job, trigger, cts.Token).ConfigureAwait(true);

            await scheduler.Start().ConfigureAwait(true);

            Console.WriteLine("======================");
            Console.WriteLine("Press Enter to exit...");
            Console.WriteLine("======================");
            Console.ReadLine();

            cts.Cancel();
            await scheduler.Shutdown().ConfigureAwait(true);
        }

        public void Stop()
        {
            Console.WriteLine("SampleSchedule Stoped!");
            logger.Info("SampleSchedule Stoped!");
        }
    }
}
